package com.link510.aitools.core.helper;

import com.blankj.utilcode.util.NetworkUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import lombok.Getter;
import lombok.Setter;

public class Network2kUtils {


    private static Network2kUtils instance = null;

    @Getter
    private Set<String> corbroadIPAddrList = Sets.newHashSet();

    private String localCurrentIpAddr = "";

    @Setter
    @Getter
    private String localCoreBroadIpAddr = "";

    private Lock lock = new ReentrantLock();

    public static Network2kUtils getInstance() {

        if (instance == null) {

            synchronized (Network2kUtils.class) {

                if (instance == null) {
                    instance = new Network2kUtils();
                }
            }
        }

        return instance;
    }

    private Network2kUtils() {
    }

    /**
     * TODO<获取本机IP前缀>
     *
     * @return String
     */
    public String getLocAddrHead() {


        if (!this.getLocalCurrentIpAddr().equals("")) {
            return this.getLocalCurrentIpAddr().substring(0, this.getLocalCurrentIpAddr().lastIndexOf(".") + 1);
        }

        return null;
    }

    /**
     * 检测IP端口是否开启监听
     *
     * @param ipAddress ip头
     * @param port      端口
     * @return 返回
     */
    public int call(String ipAddress, int port) {

        lock.lock();
        try {

            Socket connect = new Socket();
            SocketAddress remoteAddr = new InetSocketAddress(ipAddress, 5050);
            connect.connect(remoteAddr, 30);

            connect.close();
            Logger.e("Open port:" + ipAddress + " "
                    + port);

            return 0;

        } catch (UnknownHostException e) {
            Logger.e("Unknown Port：" + ipAddress + " "
                    + port);
            return -3;
        } catch (IOException e) {
            Logger.e("Unknown Port：" + ipAddress + " "
                    + port);
            return -2;
        } catch (Exception ex) {
            Logger.e("Unknown Port：" + ipAddress + " "
                    + port);

            ex.printStackTrace();
        } finally {
            lock.unlock();
        }

        Logger.e("Finished!");
        return -1;

    }


    /**
     * 获取当前IP
     *
     * @return
     */
    public String getLocalCurrentIpAddr() {

        if (Strings.isNullOrEmpty(this.localCurrentIpAddr)) {
            synchronized (Network2kUtils.class) {
                if (Strings.isNullOrEmpty(this.localCurrentIpAddr)) {
                    this.localCurrentIpAddr = NetworkUtils.getIpAddressByWifi();
                }
            }
        }

        return this.localCurrentIpAddr;
    }

    public void searchCorbroadIP() {

        String locAddrHead = Network2kUtils.getInstance().getLocAddrHead();

        for (int i = 1; i <= 255; i++) {

            String tempAddressIp = locAddrHead + i;

            Integer result = Network2kUtils.getInstance().call(tempAddressIp, 5050);

            if (result.equals(0)) {

                Network2kUtils.getInstance().getCorbroadIPAddrList().add(tempAddressIp);

                if (Strings.isNullOrEmpty(Network2kUtils.getInstance().getLocalCoreBroadIpAddr())) {
                    Network2kUtils.getInstance().setLocalCoreBroadIpAddr(tempAddressIp);
                }
            }
        }
    }
}
